<template>
    <div>
        <el-card shadow="always" :body-style="{ padding: '20px' }" style="margin-bottom: 20px">
            <CategorySelector :disabled="isShowAttrList"></CategorySelector>
        </el-card>
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <div v-show="!isShowAttrList">
                <el-button type="primary" size="default" icon="ele-Plus" style="margin-bottom: 10px" @click="addAttr" :disabled="!categoryId3" v-has="'btn.Attr.add'">添加属性</el-button>
                <el-table :data="attrList" border stripe>
                    <el-table-column type="index" width="80" label="序号" align="center" />
                    <el-table-column prop="attrName" width="150" label="属性名称" />
                    <el-table-column prop="" label="属性值列表">
                        <template v-slot="{ row }">
                            <el-tag style="margin: 0 5px" v-for="item in row.attrValueList" :key="item.id" type="danger" size="default" effect="dark">{{ item.valueName }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180">
                        <template v-slot="{ row }">
                            <el-button type="warning" size="small" @click="updateAttr(row)" icon="ele-Edit" v-has="'btn.Attr.update'"></el-button>
                            <el-button type="danger" size="small" @click="deleteAttr(row.id)" icon="ele-Delete" v-has="'btn.Attr.remove'"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-show="isShowAttrList">
                <el-form label-width="80px" :inline="true">
                    <el-form-item label="属性名" placeholder="请输入属性名">
                        <el-input v-model="attrForm.attrName" :disabled="!!attrForm.id"></el-input>
                    </el-form-item>
                </el-form>
                <div style="margin-bottom: 30px">
                    <el-button type="primary" @click="addAttrValue" :disabled="!attrForm.attrName">添加属性值</el-button>
                    <el-button type="primary" @click="cancel">取消</el-button>
                </div>
                <el-table border stripe :data="attrForm.attrValueList">
                    <el-table-column type="index" width="50" label="序号" />
                    <el-table-column label="属性值名称">
                        <template v-slot="{ row, $index }">
                            <el-input type="text" clearable v-model="row.valueName" v-if="row.isEdit" @blur="toLook(row, $index)" ref="inputRef" />
                            <span v-else @click="toEdit(row)">{{ row.valueName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="{ row, $index }">
                            <el-popconfirm title="你确定要删除吗?" @confirm="deleteAttrValue(row, $index)">
                                <template #reference>
                                    <el-button type="danger" size="small" icon="ele-Delete"></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="margin-top: 30px">
                    <el-button type="primary" @click="saveAttr" :disabled="attrForm.attrValueList.length === 0">保存</el-button>
                    <el-button type="primary" @click="cancel">取消</el-button>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "Attr",
});
</script>

<script setup lang="ts">
import { nextTick, ref, watchEffect } from "vue";
import { useCategoryStore } from "@/stores/category";
import type { AttrListType, AttrType, AttrValueType } from "@/types/attr";
import { reqAddOrUpdateAttr, reqAttrList, reqDeleteAttr } from "@/api/attr";
import { storeToRefs } from "pinia";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";

const attrList = ref<AttrType>([]); // 保存属性列表
const categoryStore = useCategoryStore(); // 获取分类数据
const { categoryId1, categoryId2, categoryId3 } = storeToRefs(categoryStore);

// 获取属性列表
const getAttrList = async () => {
    try {
        attrList.value = await reqAttrList(categoryId1.value as number, categoryId2.value as number, categoryId3.value as number);
    } catch (e) {
        ElMessage.error("获取属性列表失败");
    }
};

// 监听categoryId3发生改变获取属性列表,如果categoryId3为空,则不获取属性列表
watchEffect(() => {
    if (categoryId3.value) {
        getAttrList();
    } else {
        attrList.value = [];
    }
});
// 删除属性
const deleteAttr = async (id: number) => {
    try {
        await ElMessageBox.confirm("确定删除该属性吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(async () => {
            try {
                await reqDeleteAttr(id);
                ElMessage.success("删除属性成功");
                // 删除成功后重新获取属性列表
                await getAttrList();
            } catch (e) {
                ElMessage.error("删除属性失败");
            }
        });
    } catch (e) {
        ElMessage.error("你不删除了?");
    }
};

// 控制添加属性和属性值的显示隐藏
const isShowAttrList = ref(false);
// 添加属性的数据
const attrForm = ref<AttrListType>({
    attrName: "", // 属性名
    attrValueList: [], // 属性值列表
    categoryId: categoryId3.value as number, // 三级分类id
    categoryLevel: 3, // 分类级别
});
// 添加属性值
const addAttrValue = () => {
    attrForm.value.attrValueList.push({
        valueName: "",
        // attrId: 0, // 新添加的属性id为0
        attrId: attrForm.value.id,
        isEdit: true, // 是否可编辑
    });
    // 添加自动聚焦
    nextTick(() => {
        inputRef.value?.focus();
    });
};
// 添加属性事件回调
const addAttr = () => {
    isShowAttrList.value = true;
    // 每次添加属性时,清空属性值列表
    attrForm.value = {
        attrName: "", // 属性名
        attrValueList: [], // 属性值列表
        categoryId: categoryId3.value as number, // 三级分类id
        categoryLevel: 3, // 分类级别
    };
};
// 点击某个属性修改属性值
const updateAttr = (row: AttrListType) => {
    isShowAttrList.value = true;
    attrForm.value = cloneDeep(row); // 需要对row进行深拷贝,否则会影响原来的数据
    // 修改属性的时候，改变已经存在的模式属性isEdit为false
    attrForm.value.attrValueList.forEach(item => {
        item.isEdit = false;
    });
};

// 点击切换查看和编辑模式,并自动获取焦点
const inputRef = ref<HTMLInputElement>();
const toLook = (row: AttrValueType, index: number) => {
    row.isEdit = false;
    // 判断进入的是添加还是修改操作
    if (!row.id) {
        // 添加操作
        // 如果该属性值为空,则删除该属性值
        if (!row.valueName) {
            ElMessage.error("属性值不能为空");
            attrForm.value.attrValueList.splice(index, 1);
        }
    } else {
        // 修改操作
        // 如果该属性值为空,则恢复原来的属性值
        if (!row.valueName) {
            // 先找到该属性值在原来的属性值列表中的属性值
            const attrValue = attrList.value.find(item => item.id === row.attrId)?.attrValueList.find(item => item.id === row.id);
            // 如果找到了,则恢复原来的属性值
            if (attrValue) {
                row.valueName = attrValue.valueName;
            }
        }
    }
    // 如果该属性值和已有属性值相同,则删除该属性值
    attrForm.value.attrValueList.forEach((item, i) => {
        if (i !== index && item.valueName === row.valueName) {
            ElMessage.error("该属性值已存在");
            attrForm.value.attrValueList.splice(index, 1);
        }
    });
};
const toEdit = (row: AttrValueType) => {
    row.isEdit = true;
    // 自动获取焦点
    nextTick(() => {
        inputRef.value?.focus();
    });
};

// 删除属性值
const deleteAttrValue = (row: AttrValueType, index: number) => {
    attrForm.value.attrValueList.splice(index, 1);
};

// 保存属性
const saveAttr = async () => {
    // 提交之前,清除isEdit属性(因为isEdit属性不需要提交到后台)
    attrForm.value.attrValueList.forEach(item => {
        delete item.isEdit;
    });
    try {
        // 如果属性id存在,则为修改属性,否则为添加属性
        if (attrForm.value.id) {
            // 修改属性
            await reqAddOrUpdateAttr(attrForm.value);
            ElMessage.success("修改属性成功");
        } else {
            // 添加属性
            await reqAddOrUpdateAttr(attrForm.value);
            ElMessage.success("添加属性成功");
        }
        isShowAttrList.value = false;
        // 保存成功后重新获取属性列表
        await getAttrList();
    } catch (e) {
        ElMessage.error("保存失败");
    }
};
// 取消的回调
const cancel = () => {
    isShowAttrList.value = false;
    // // 取消的时候,重新获取属性列表
    // getAttrList();
};
</script>

<style scoped></style>
